import React, { useEffect, useRef, useState } from "react";
import {
  Form,
  Row,
  Col,
  Button,
  Space,
  Input,
  message,
  Spin,
  Select,
} from "antd";
import UploadImgX from "../uploadx";
import { changeDrawerState } from "@/store/modules/themeStore";
import { useAppDispatch, useAppSelector } from "@/store/hook.ts";
import { uploadCenterInfo, updateCenterInfo } from "@/api/api_center";
import { changeupdateState } from "@/store/modules/assStore";
const type = "Center";

interface ChildMethods {
  handleUpload: () => void;
}

function CenterItem({ assInfo }) {
  const isAdd = useAppSelector((state) => state.ass.isAdd);
  const update = useAppSelector((state) => state.ass.update);
  const [form] = Form.useForm();
  useEffect(() => {
    if (!isAdd) {
      const {
        manufacturers,
        series,
        cpu_slot,
        memory_type,
        pci_e,
        pci_e_slot,
        video_interface,
        power_interface,
        memory_interface,
        price,
        score,
        capacity,
        memory_sum,
      } = assInfo;

      const data = {
        centerManufacturer: manufacturers,
        series,
        cpu_slot,
        type: memory_type,
        sum: memory_sum,
        capacity,
        pci_e,
        pci_e_slot,
        video_interface,
        power_interface,
        price,
        score,
        memory_interface,
      };
      form.setFieldsValue(data);
    } else {
      form.resetFields();
    }
  }, [isAdd, assInfo, form]);

  //CENTER TSX
  const Center = {
    MANUFACTURERS: (
      <Form.Item
        name="centerManufacturer"
        label="主板厂商"
        rules={[
          {
            required: true,
            message: "Please select your centerManufacturer!",
          },
        ]}
      >
        <Select
          options={[
            { value: "ASUS", label: "ASUS 华硕" },
            { value: "Gigabyte", label: "Gigabyte 技嘉" },
            { value: "MSI", label: "MSI 微星" },
            { value: "other", label: "其他" },
          ]}
        />
      </Form.Item>
    ),
    SERIES: (
      <Form.Item
        name="series"
        label="主板型号"
        rules={[{ required: true, message: "Please input codeName!" }]}
      >
        <Input />
      </Form.Item>
    ),
    CPU_SLOT: (
      <Form.Item
        name="cpu_slot"
        label="CPU插槽"
        rules={[{ required: true, message: "Please select cpu_slot!" }]}
      >
        <Input />
      </Form.Item>
    ),
    Memory_Type: (
      <Form.Item label="内存类型">
        {/* <Space> */}
        <Space.Compact style={{ width: "100%" }}>
          <Form.Item
            style={{ width: "20%" }}
            name="sum"
            rules={[{ required: true, message: "请选择数量" }]}
          >
            <Select
              options={[
                { value: "1", label: "1" },
                { value: "2", label: "2" },
                { value: "3", label: "3" },
                { value: "4", label: "4" },
              ]}
            />
          </Form.Item>
          <Form.Item
            style={{ width: "50%" }}
            name="type"
            rules={[{ required: true, message: "请选择类型" }]}
          >
            <Select
              options={[
                { value: "DDR3", label: "DDR3 DIMM" },
                { value: "DDR4", label: "DDR4 DIMM" },
                { value: "DDR5", label: "DDR5 DIMM" },
                { value: "DDR6", label: "DDR6 DIMM" },
                { value: "DDR6X", label: "DDR6X DIMM" },
                { value: "other", label: "其他" },
              ]}
            />
          </Form.Item>
          <Form.Item
            style={{ width: "30%" }}
            name="capacity"
            rules={[{ required: true, message: "请输入最大容量" }]}
          >
            <Input suffix="GB" />
          </Form.Item>
        </Space.Compact>
        {/* </Space> */}
      </Form.Item>
    ),
    PCI_E: (
      <Form.Item
        name="pci_e"
        label="PCI_E标准"
        rules={[{ required: true, message: "Please select pci_e!" }]}
      >
        <Input />
      </Form.Item>
    ),
    PCI_E_SLOT: (
      <Form.Item
        name="pci_e_slot"
        label="PCI_E插槽"
        rules={[{ required: true, message: "Please input pci_e_slot!" }]}
      >
        <Input />
      </Form.Item>
    ),
    VIDEOINTERFACE: (
      <Form.Item
        name="video_interface"
        label="视频接口"
        rules={[{ required: true, message: "Please input video_interface!" }]}
      >
        <Input />
      </Form.Item>
    ),
    POWERINTERFACE: (
      <Form.Item
        name="power_interface"
        label="电源接口"
        rules={[{ required: true, message: "Please input power_interface!" }]}
      >
        <Input />
      </Form.Item>
    ),
    MEMORYINTERFACE: (
      <Form.Item
        name="memory_interface"
        label="内存接口"
        rules={[{ required: true, message: "Please input memory_interface!" }]}
      >
        <Input />
      </Form.Item>
    ),
    PRICE: (
      <Form.Item name="price" label="市场估价" rules={[{ required: true }]}>
        <Input prefix="￥" suffix="RMB" />
      </Form.Item>
    ),
    SCORE: (
      <Form.Item
        name="score"
        label="性能评分"
        rules={[{ required: true, message: "Please input score!" }]}
      >
        <Input />
      </Form.Item>
    ),
  };
  const childRef = useRef<ChildMethods>(null); // 创建一个 ref 来引用子组件

  const [spinning, setSpinning] = useState(false);

  const dispatch = useAppDispatch();

  // 表单验证
  const validateMessages = {
    required: "${label} is required!",
    types: {
      email: "${label} is not a valid email!",
      number: "${label} is not a valid number!",
    },
    number: {
      range: "${label} must be between ${min} and ${max}",
    },
  };

  // 表单提交
  const onFinish = async (values: any) => {
    setSpinning(true);
    const img_url_arr = await handleImageUpload();
    handleFormSubmit(values, img_url_arr as string[]);
  };

  //弹窗的状态控制
  const onClose = () => {
    dispatch(changeDrawerState(false));
  };

  //上传图片
  const handleImageUpload = async () => {
    if (childRef.current) {
      const result = childRef.current.handleUpload();
      return result;
    } else {
      return [];
    }
  };

  //添加Center信息
  const handleFormSubmit = async (values: any, img_url_arr: string[]) => {
    try {
      const info = {
        manufacturers: values.centerManufacturer,
        series: values.series,
        cpu_slot: values.cpu_slot,
        memory_sum: values.sum,
        memory_type: values.type,
        capacity: values.capacity,
        pci_e: values.pci_e,
        pci_e_slot: values.pci_e_slot,
        video_interface: values.video_interface,
        power_interface: values.power_interface,
        memory_interface: values.memory_interface,
        price: parseFloat(values.price),
        img_url_arr,
        score: parseFloat(values.score),
      };
      if (!isAdd) {
        await updateCenterInfo(assInfo._id, info);
        message.success("更新成功");
      } else {
        await uploadCenterInfo(info);
        message.success("添加成功");
      }
      setSpinning(false);
      form.resetFields();
      dispatch(changeupdateState(!update));
      dispatch(changeDrawerState(false));
    } catch (error) {
      console.error(error);
      message.error("添加失败，请重试");
    }
  };

  return (
    <>
      <Spin spinning={spinning} fullscreen />
      <Form
        form={form}
        layout="vertical"
        onFinish={onFinish}
        validateMessages={validateMessages}
      >
        {/* 详情图 */}

        <Form.Item>
          <div style={{ fontWeight: "bold", marginBottom: 10 }}>详情图</div>
          <UploadImgX ref={childRef} type={type} />
        </Form.Item>

        {/* GPU主要信息 */}
        <Row gutter={16}>
          <Col span={12}>{Center.MANUFACTURERS}</Col>
          <Col span={12}>{Center.SERIES}</Col>
          <Col span={12}>{Center.CPU_SLOT}</Col>
          <Col span={12}>{Center.Memory_Type}</Col>
          <Col span={12}>{Center.PCI_E}</Col>
          <Col span={12}>{Center.PCI_E_SLOT}</Col>
          <Col span={12}>{Center.VIDEOINTERFACE}</Col>
          <Col span={12}>{Center.POWERINTERFACE}</Col>
          <Col span={12}>{Center.MEMORYINTERFACE}</Col>
          <Col span={12}>{Center.SCORE}</Col>
          <Col span={12}>{Center.PRICE}</Col>
        </Row>
        <Form.Item>
          <Space size="large">
            <Button type="primary" danger htmlType="reset" onClick={onClose}>
              取消
            </Button>
            <Button type="primary" htmlType="submit">
              {isAdd ? "添加" : "更新"}
            </Button>
          </Space>
        </Form.Item>
      </Form>
    </>
  );
}

export default CenterItem;
